package com.atguigu.gmall.cart.service.impl;

import com.atguigu.gmall.cart.mapper.CartInfoMapper;
import com.atguigu.gmall.cart.service.CartAsyncService;
import com.atguigu.gmall.model.cart.CartInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class CartAsyncServiceImpl implements CartAsyncService {
    @Autowired
    private CartInfoMapper cartInfoMapper;

    @Override
    @Async
    //@Transactional(rollbackFor = Exception.class)
    public void updateCartInfo(CartInfo cartInfo) {
        /*利用userId 和 skuId 为唯一键代替主键，防止由于 存入mysql是异步的滞后性，导致存入redis
        * 时的CartInfo对象id 没有主键回填，则再从redis中获取时，没有主键id，则updateById有问题。
        * */

        QueryWrapper<CartInfo> cartInfoQueryWrapper = new QueryWrapper<>();
        cartInfoQueryWrapper.eq("user_id",cartInfo.getUserId());
        cartInfoQueryWrapper.eq("sku_id",cartInfo.getSkuId());
        cartInfoMapper.update(cartInfo,cartInfoQueryWrapper);

    }

    @Override
    @Async
    //@Transactional(rollbackFor = Exception.class)
    public void  saveCartInfo(CartInfo cartInfo) {

        cartInfoMapper.insert(cartInfo);

    }

    //根据用户id删除该用户对应购物车
    @Override
    @Async
    public void deleteCartInfoByUserId(String userId) {
        QueryWrapper<CartInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        cartInfoMapper.delete(queryWrapper);
    }

    //更改选中状态
    @Override
    @Async
    public void checkCart(String userId, Integer isChecked, Long skuId) {
        CartInfo cartInfo = new CartInfo();
        UpdateWrapper<CartInfo> cartInfoUpdateWrapper = new UpdateWrapper<>();
        cartInfoUpdateWrapper.eq("user_id", userId);
        cartInfoUpdateWrapper.eq("sku_id", skuId);
        cartInfoUpdateWrapper.set("is_checked",isChecked);
        cartInfoMapper.update(cartInfo,cartInfoUpdateWrapper);
    }

    //删除某用户指定的购物车商品
    @Override
    @Async
    public void deleteCartInfo(String userId, Long skuId) {
        QueryWrapper<CartInfo> cartInfoQueryWrapper = new QueryWrapper<>();
        cartInfoQueryWrapper.eq("user_id", userId);
        cartInfoQueryWrapper.eq("sku_id", skuId);
        cartInfoMapper.delete(cartInfoQueryWrapper);
    }
}
